package com.tanjie.blackbean.core.web;

import com.tanjie.blackbean.pojo.auth.AuthConst;
import com.tanjie.blackbean.pojo.auth.UserInfo;
import com.tanjie.blackbean.pojo.exception.AuthException;
import com.tanjie.blackbean.pojo.response.AuthErrorCode;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

/**
 * @author: tanjie
 * @date: 2022-04-29
 **/
public abstract class BlackbeanRequestContextHolder {

    private BlackbeanRequestContextHolder() {
    }

    public static String getOrgIdThr() {
        return getUserInfoThr().getOrgId();
    }

    public static String getUserIdThr() {
        return getUserInfoThr().getId();
    }

    public static UserInfo getUserInfoThr() {
        Object userInfoObj = getRequestAttribute(AuthConst.USER_INFO);
        if (userInfoObj == null) {
            throw new AuthException(AuthErrorCode.CANNOT_GET_USERINFO_FROM_TOKEN);
        }
        return (UserInfo) userInfoObj;
    }

    public static UserInfo getUserInfo() {
        Object o = getRequestAttribute(AuthConst.USER_INFO);
        if (o != null) {
            return (UserInfo) o;
        }
        return null;
    }

    public static String getUserId() {
        UserInfo userInfo = getUserInfo();
        if (userInfo != null) {
            return userInfo.getId();
        }
        return null;
    }

    public static Object getRequestAttribute(String attributeName) {
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        return requestAttributes.getAttribute(attributeName, RequestAttributes.SCOPE_REQUEST);
    }

}
